package com.aaa.doctor.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.aaa.doctor.dao.SchedulingDao;
import com.aaa.doctor.feign.UserFeign;
import com.aaa.doctor.service.SchedulingService;
import com.aaa.doctor.vo.Scheduling2Vo;
import com.aaa.doctor.vo.SchedulingDto;
import com.aaa.doctor.vo.SchedulingVo;
import com.aaa.doctor.vo.SchedulingVoo;
import com.aaa.entity.Scheduling;
import com.aaa.entity.User;
import com.aaa.system.dao.UserDao;
import com.aaa.utils.JWTUtils;
import com.aaa.utils.WebUtil;
import com.aaa.vo.Result;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.util.unit.DataUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @version 1.8.0_181
 * @Author ZXJ
 * @Date 2023/3/29 9:04
 * @注释
 */
@Service
public class SchedulingServiceImpl implements SchedulingService {
    @Resource
    private UserFeign userFeign;

    @Resource
    private SchedulingDao schedulingDao;



    @Override
    public Result queryScheduling(SchedulingVoo schedulingVoo) {
        //查询所有医生的信息
        Map<String,Object> map=new HashMap<>();
        map.put("userId", schedulingVoo.getUserId());
        map.put("deptId", schedulingVoo.getDeptId());
        List<User> users = userFeign.queryUserNeedScheduling(map);
        return querySchedulingByCondition(schedulingVoo, users);
    }

    @Override
    public Result queryMyScheduling(SchedulingVoo schedulingVoo) {
        //直接在token获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        System.out.println("token获取 ==================== " + token);
        Map<String, Object> tokenInfo = JWTUtils.getInfo(token);
        String phone = tokenInfo.get("username").toString();
        //通过token获取登录用户信息
        User byUsername = userFeign.getByUsername(phone);
        schedulingVoo.setUserId(byUsername.getUserId());
        //schedulingVoo.setUserId(byUsername.getUserId());
        ArrayList<User> list = new ArrayList<>();
        list.add(byUsername);

        return querySchedulingByCondition(schedulingVoo, list);
    }

    @Override
    public Result getDeptForScheduling(SchedulingVo schedulingVo) {
        QueryWrapper<Scheduling> wrapper = new QueryWrapper<>();
        //判断部门
        if (Objects.nonNull(schedulingVo.getDeptId())){
            wrapper.eq("dept_id",schedulingVo.getDeptId());
        }
        //挂号类型(门急诊)
        if (Objects.nonNull(schedulingVo.getSchedulingType())){
            wrapper.eq("scheduling_type",schedulingVo.getSchedulingType());
        }
        //挂号时段
        if(StringUtils.hasText(schedulingVo.getSubsectionType())){
            wrapper.eq("subsection_type",schedulingVo.getSubsectionType());
        }
        System.out.println("--------------------"+JSON.toJSONString(schedulingVo.getSchedulingDay()));
        if (Objects.nonNull(schedulingVo.getSchedulingDay())){
            wrapper.eq("scheduling_day",schedulingVo.getSchedulingDay());

        }

        List<Scheduling> schedulings = schedulingDao.selectList(wrapper);
        return new Result<>(200,"所有排班信息查询成功",schedulings);
    }

    @Override//修改排班
    public Result editScheduling(Scheduling2Vo scheduling2Vo) {
        // 查询出账号登陆者的姓名
        HttpServletRequest request = WebUtil.getRequest();
        String phone = (String) JWTUtils.getInfo(request.getHeader("token")).get("username");
        String userName = userFeign.getByUsername(phone).getUserName();
        // 获取传输的数据
        List<SchedulingDto> allDatas = scheduling2Vo.getAllDatas();
        //String beginDate = scheduling2Vo.getBeginDate();

//        int del = 1;
//        int update = 1;
        DateTime dateTime = DateUtil.parse(scheduling2Vo.getBeginDate(), "yyyy-MM-dd");
        Map<String, String> map = initMap(dateTime);
        Set<String> keys = map.keySet();

        // 遍历
        for (SchedulingDto allData : allDatas) {
            // 删除
            QueryWrapper<Scheduling> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", allData.getUserId());
            wrapper.eq("subsection_type", allData.getSubsectionType());
            wrapper.between("scheduling_day", scheduling2Vo.getBeginDate(), scheduling2Vo.getEndDate());
            schedulingDao.delete(wrapper);//没有主键 进行删除

            Collection<String> schedulingType = allData.getSchedulingType();//获取排班
            Iterator<String> scheduling = schedulingType.iterator();//排班 1门诊  2急诊
            Iterator<String> key = keys.iterator();//获取当前的日期
            for (int i = 0; i < keys.size(); i++) {
                String next = scheduling.next();//指向下一条记录
                String next1 = key.next();
                if (!next.equals("")) {
                    Scheduling user = new Scheduling();
                    user.setUserId(allData.getUserId());
                    user.setDeptId(allData.getDeptId());
                    user.setSubsectionType(allData.getSubsectionType());
                    user.setSchedulingDay(next1);
                    user.setSchedulingType(next);
                    user.setCreateBy(userName);
                    LocalDateTime date = LocalDateTime.now();//时间转换
                    user.setCreateTime(date);
                    schedulingDao.insert(user);
                }
            }
        }
        return new Result(200, "成功", null);
    }


    //封装前端需要的数据
    private Result querySchedulingByCondition(SchedulingVoo schedulingVoo, List<User> users) {
        //获取当前时间
        DateTime date = DateUtil.date();
        if (StringUtils.hasText(schedulingVoo.getQueryDate())){
            date=DateUtil.parse(schedulingVoo.getQueryDate(),"yyyy-MM-dd");//字符串转date类型
            int i = DateUtil.dayOfWeek(date);//获取当前周的第几天  返回的是2表示周一   返回一1表示周日
            if (i == 1) {
                 date = DateUtil.offsetDay(date, 1);
            }else {
                 date=DateUtil.offsetDay(date,-1);
            }
        }
        //这一周的开始时间和结束时间
        DateTime beginDate = DateUtil.beginOfWeek(date);//这一周的开始时间
        DateTime endDate = DateUtil.endOfWeek(date);//结束时间
        schedulingVoo.setBeginDate(DateUtil.format(beginDate,"yyyy-MM-dd"));
        schedulingVoo.setEndDate(DateUtil.format(endDate,"yyyy-MM-dd"));
        //根据条件查询排班表
        List<Scheduling> schedulings = queryByCondition(schedulingVoo);

        List<SchedulingDto> schedulingDtos=new ArrayList<>();//存放一条一条记录
        //根据用户进行遍历
        for (User user:users){
            SchedulingDto schedulingDto1 = new SchedulingDto(user.getUserId(),user.getDeptId(),"1",initMap(beginDate));
            SchedulingDto schedulingDto2 = new SchedulingDto(user.getUserId(),user.getDeptId(),"2",initMap(beginDate));
            SchedulingDto schedulingDto3 = new SchedulingDto(user.getUserId(),user.getDeptId(),"3",initMap(beginDate));
            //一个用户都有这三条数据
            schedulingDtos.add(schedulingDto1);
            schedulingDtos.add(schedulingDto2);
            schedulingDtos.add(schedulingDto3);
            for (Scheduling scheduling:schedulings){
                //获取用户id
                Long userId = scheduling.getUserId();
                String schedulingDay = scheduling.getSchedulingDay();//排班日期
                String subsectionType = scheduling.getSubsectionType();//排班类型
                if(user.getUserId().equals(userId)) {
                    switch (subsectionType) {
                        case "1":
                            Map<String, String> record1 = schedulingDto1.getRecord();
                            record1.put(schedulingDay, scheduling.getSchedulingType());
                            break;
                        case "2":
                            Map<String, String> record2 = schedulingDto2.getRecord();
                            record2.put(schedulingDay, scheduling.getSchedulingType());
                            break;
                        case "3":
                            Map<String, String> record3 = schedulingDto3.getRecord();
                            record3.put(schedulingDay, scheduling.getSchedulingType());
                            break;
                    }
                }
            }
            schedulingDto1.setSchedulingType(schedulingDto1.getRecord().values());
            schedulingDto2.setSchedulingType(schedulingDto2.getRecord().values());
            schedulingDto3.setSchedulingType(schedulingDto3.getRecord().values());
        }
        //封装表数据
        Map<String,Object> result=new HashMap<>();
        result.put("tableDate",schedulingDtos);
        result.put("beginDate",DateUtil.format(beginDate,"yyyy-MM-dd"));
        result.put("endDate",DateUtil.format(endDate,"yyyy-MM-dd"));
        //表头
        Object label = initLabel(beginDate);
        result.put("labelNames",label);
        return new Result(200,"查询医生排班成功",result);

    }
    //封装标题
    private Object initLabel(DateTime beginTime) {
        String[] labelNames = new String[7];
        for (int i = 0; i < 7; i++) {
            DateTime d = DateUtil.offsetDay(beginTime, i);
            labelNames[i] = DateUtil.format(d,"yyyy-MM-dd") + formatterWeek(i);
        }
        return labelNames;
    }

    private String formatterWeek(int i) {
        switch (i) {
            case 0:
                return "(周一)";
            case 1:
                return "(周二)";
            case 2:
                return "(周三)";
            case 3:
                return "(周四)";
            case 4:
                return "(周五)";
            case 5:
                return "(周六)";
            default:
                return "(周日)";
        }
    }
    //初始化当前用户这一周的排班信息
    private static Map<String, String> initMap(DateTime beginDate) {
        Map<String,String> map=new TreeMap<>();//treemap有序
        for (int i = 0; i < 7; i++) {
            DateTime dateTime = DateUtil.offsetDay(beginDate, i);
            String key = DateUtil.format(dateTime, "yyyy-MM-dd");
            map.put(key,"");
        }
        return map;
    }

    //根据条件查询排班信息
    public List<Scheduling> queryByCondition(SchedulingVoo schedulingVoo){
        QueryWrapper<Scheduling> wrapper = new QueryWrapper<>();
        if (schedulingVoo.getUserId()!=null){
            wrapper.eq("user_id",schedulingVoo.getUserId());
        }
        if (schedulingVoo.getDeptId() != null) {
            wrapper.eq("dept_id",schedulingVoo.getDeptId());
        }
        if (StringUtils.hasText(schedulingVoo.getBeginDate())){
            wrapper.ge("scheduling_day",schedulingVoo.getBeginDate());
            //      >=
        }
        if (StringUtils.hasText(schedulingVoo.getEndDate())){
            wrapper.le("scheduling_day",schedulingVoo.getEndDate());
            //     <=
        }
        return  schedulingDao.selectList(wrapper);
    }


}
